package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.WebUtils;
import core.Lookup;
import core.NearbyServicesLocal;

public class SearchCategory extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
	
		Integer idCategory = WebUtils.safeGetParameterInteger(req, "idCategory");
		Double latitude = WebUtils.safeGetParameterDouble(req, "latitude");
		Double longitude = WebUtils.safeGetParameterDouble(req, "longitude");
		Double radious = WebUtils.safeGetParameterDouble(req, "radious");
		
		NearbyServicesLocal nearbyServices = Lookup.lookupNearbyServices();
		
		List<Category> categories = nearbyServices.getCategories(idCategory, latitude, longitude, radious);
		
		JSONArray jsonArray = new JSONArray();
		
		for (Category category : categories) {
			try {
				jsonArray.put(new JSONObject(category.toString()));
			} catch (JSONException e) {
				throw new ServletException(e);
			}
		}
		
		String outputString = jsonArray.toString();
		
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/html;charset=UTF-8");
		writer.print(outputString);
		writer.close();
	}

}
